package header

import (
	"github.com/sirupsen/logrus"
	"strings"
	"udp_tcp_client/sip/header/common"
	"udp_tcp_client/util"
)

// Via信息列表
type ViaList struct {
	value             []Via  // 内部实际的值
	receivedTransport string // 接收时的协议
	receivedAddr      string // 接收时的实际地址
}

// 添加一条记录
func (vl *ViaList) Add(item Via) (err error) {
	vl.value = append(vl.value, item)
	return
}

func (vl *ViaList) AddString(str string) (err error) {
	item, err := parseVia(str)
	if err != nil {
		return
	}
	vl.value = append(vl.value, item)
	return
}

func (vl *ViaList) GetPreVia() Via {
	return vl.value[len(vl.value)-1]
}

func parseVia(str string) (item Via, err error) {
	str = strings.TrimSpace(str)
	item = Via{}

	parts := strings.Split(str, util.BRANCH)
	if len(parts) == 0 {
		logrus.Error("via转换失败")
		return item, nil
	}

	sipInfo := strings.Split(parts[0], util.BLANK)
	sipInfoChild := strings.Split(sipInfo[0], util.SLASH)

	item.SIPVersion = sipInfoChild[0] + util.SLASH + sipInfoChild[1]
	item.Transport = sipInfoChild[2]
	item.Client = sipInfo[1]

	for i := 1; i < len(parts); i++ {
		item.Arguments = common.ParseArgs(parts[i])
	}

	return
}
